<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Java中的反射 | CodingDGSun's Blog</title><meta name="author" content="CodingDGSun"><meta name="copyright" content="CodingDGSun"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Java反射机制，是在程序的运行过程中，对于任何一个类，都能够知道它的所有属性和方法。对于任意一个对象，都能够知道调用他的任意属性和方法。这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制。 如下代码示例：  父类Animal  1234567891011121314151617181920212223package com.study.reflection;public cla">
<meta property="og:type" content="article">
<meta property="og:title" content="Java中的反射">
<meta property="og:url" content="https://sunjie23.gitee.io/codingdgsun/2021/07/06/Java%E4%B8%AD%E7%9A%84%E5%8F%8D%E5%B0%84/index.html">
<meta property="og:site_name" content="CodingDGSun&#39;s Blog">
<meta property="og:description" content="Java反射机制，是在程序的运行过程中，对于任何一个类，都能够知道它的所有属性和方法。对于任意一个对象，都能够知道调用他的任意属性和方法。这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制。 如下代码示例：  父类Animal  1234567891011121314151617181920212223package com.study.reflection;public cla">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg">
<meta property="article:published_time" content="2021-07-06T05:59:27.000Z">
<meta property="article:modified_time" content="2021-07-06T06:22:31.038Z">
<meta property="article:author" content="CodingDGSun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg"><link rel="shortcut icon" href="/codingdgsun/img/favicon.png"><link rel="canonical" href="https://sunjie23.gitee.io/codingdgsun/2021/07/06/Java%E4%B8%AD%E7%9A%84%E5%8F%8D%E5%B0%84/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/codingdgsun/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/codingdgsun/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java中的反射',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2021-07-06 14:22:31'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/codingdgsun/atom.xml" title="CodingDGSun's Blog" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://cdn.jsdelivr.net/gh/CodingDGSun/images-db@master/Blog/头像.7horht40yvwg.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/codingdgsun/archives/"><div class="headline">Articles</div><div class="length-num">59</div></a></div></div></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/codingdgsun/">CodingDGSun's Blog</a></span><div id="menus"><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java中的反射</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2021-07-06T05:59:27.000Z" title="Created 2021-07-06 13:59:27">2021-07-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2021-07-06T06:22:31.038Z" title="Updated 2021-07-06 14:22:31">2021-07-06</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java中的反射"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><strong>Java反射机制，是在程序的运行过程中，对于任何一个类，都能够知道它的所有属性和方法。对于任意一个对象，都能够知道调用他的任意属性和方法。这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制。</strong></p>
<p>如下代码示例：</p>
<ul>
<li>父类Animal</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">package com.study.reflection;</span><br><span class="line"></span><br><span class="line">public class Animal &#123;</span><br><span class="line">    public String name;</span><br><span class="line">    public int age;</span><br><span class="line"></span><br><span class="line">    public Animal() &#123;</span><br><span class="line">        super();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Animal(String name, int age) &#123;</span><br><span class="line">        this.name = name;</span><br><span class="line">        this.age = age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void eat() &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String getInfo() &#123;</span><br><span class="line">        return &quot;name:&quot; + this.name + &quot;, age:&quot; + age;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>子类Cat，继承Animal</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">package com.study.reflection;</span><br><span class="line"></span><br><span class="line">public class Cat extends Animal &#123;</span><br><span class="line">    public String color;</span><br><span class="line">    private String owner;</span><br><span class="line">    String sex;</span><br><span class="line"></span><br><span class="line">    public Cat() &#123;</span><br><span class="line">        super();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Cat(String name, int age, String color, String owner) &#123;</span><br><span class="line">        super(name, age);</span><br><span class="line">        this.color = color;</span><br><span class="line">        this.owner = owner;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Cat(String owner) &#123;</span><br><span class="line">        this.owner = owner;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String getColor() &#123;</span><br><span class="line">        return color;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setColor(String color) &#123;</span><br><span class="line">        this.color = color;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    void mie() &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private void smile() &#123;</span><br><span class="line">        System.out.println(name + &quot;在笑&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void cry() &#123;</span><br><span class="line">        System.out.println(name + &quot;在哭&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public String toString() &#123;</span><br><span class="line">        return &quot;姓名：&quot; + this.name + &quot;, 年龄：&quot; + this.age + &quot;, 颜色：&quot; + color + &quot;, 主人：&quot; + owner;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>测试类TestReflect</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br></pre></td><td class="code"><pre><span class="line">package com.study.reflection;</span><br><span class="line"></span><br><span class="line">import java.lang.reflect.Constructor;</span><br><span class="line">import java.lang.reflect.Field;</span><br><span class="line">import java.lang.reflect.InvocationTargetException;</span><br><span class="line">import java.lang.reflect.Method;</span><br><span class="line"></span><br><span class="line">public class TestReflect &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        Class cat = null;</span><br><span class="line">        try &#123;</span><br><span class="line">            cat = Class.forName(&quot;com.study.reflection.Cat&quot;);</span><br><span class="line">        &#125; catch (ClassNotFoundException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        //获取对象的所有公有（public）属性，例如：public String color;包括继承的父类中public修饰的属性</span><br><span class="line">        Field[] fields = cat.getFields();</span><br><span class="line">        for (Field f : fields) &#123;</span><br><span class="line">            //输出结果：</span><br><span class="line">            // public java.lang.String com.study.reflection.Cat.color</span><br><span class="line">            // public java.lang.String com.study.reflection.Animal.name</span><br><span class="line">            // public int com.study.reflection.Animal.age</span><br><span class="line">            System.out.println(f);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;==========================================================&quot;);</span><br><span class="line"></span><br><span class="line">        //获取对象所有属性（不管是public还是private或者没有修饰符的修饰的属性），但不包括继承的父类中的属性</span><br><span class="line">        Field[] declaredFields = cat.getDeclaredFields();</span><br><span class="line">        for (Field df : declaredFields) &#123;</span><br><span class="line">            //输出结果：</span><br><span class="line">            //public java.lang.String com.study.reflection.Cat.color</span><br><span class="line">            //private java.lang.String com.study.reflection.Cat.owner</span><br><span class="line">            //java.lang.String com.study.reflection.Cat.sex</span><br><span class="line">            System.out.println(df);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;==========================================================&quot;);</span><br><span class="line"></span><br><span class="line">        //获取对象的所有公共（public）方法;包括继承的父类中的public修饰的方法以及Object类中public修饰的方法</span><br><span class="line">        Method[] methods = cat.getMethods();</span><br><span class="line">        for (Method m : methods) &#123;</span><br><span class="line">            //输出结果：</span><br><span class="line">            //public java.lang.String com.study.reflection.Cat.toString()</span><br><span class="line">            //public void com.study.reflection.Cat.setColor(java.lang.String)</span><br><span class="line">            //public java.lang.String com.study.reflection.Cat.getColor()</span><br><span class="line">            //public void com.study.reflection.Cat.cry()</span><br><span class="line">            //public void com.study.reflection.Animal.eat()</span><br><span class="line">            //public java.lang.String com.study.reflection.Animal.getInfo()</span><br><span class="line">            //public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException</span><br><span class="line">            //public final void java.lang.Object.wait() throws java.lang.InterruptedException</span><br><span class="line">            //public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException</span><br><span class="line">            //public boolean java.lang.Object.equals(java.lang.Object)</span><br><span class="line">            //public native int java.lang.Object.hashCode()</span><br><span class="line">            //public final native java.lang.Class java.lang.Object.getClass()</span><br><span class="line">            //public final native void java.lang.Object.notify()</span><br><span class="line">            //public final native void java.lang.Object.notifyAll()</span><br><span class="line">            System.out.println(m);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;==========================================================&quot;);</span><br><span class="line"></span><br><span class="line">        //获取对象所有方法（不管是public还是private或者没有修饰符的修饰的方法），但不包括继承的父类中的方法</span><br><span class="line">        Method[] declaredMethods = cat.getDeclaredMethods();</span><br><span class="line">        for (Method dm : declaredMethods) &#123;</span><br><span class="line">            //输出结果：</span><br><span class="line">            //public java.lang.String com.study.reflection.Cat.toString()</span><br><span class="line">            //public void com.study.reflection.Cat.setColor(java.lang.String)</span><br><span class="line">            //public java.lang.String com.study.reflection.Cat.getColor()</span><br><span class="line">            //void com.study.reflection.Cat.mie()</span><br><span class="line">            //private void com.study.reflection.Cat.smile()</span><br><span class="line">            //public void com.study.reflection.Cat.cry()</span><br><span class="line">            System.out.println(dm);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;==========================================================&quot;);</span><br><span class="line"></span><br><span class="line">        //获取对象的所有公共（public）构造方法，但不包括继承的父类中的构造方法</span><br><span class="line">        Constructor[] constructors = cat.getConstructors();</span><br><span class="line">        for (Constructor c : constructors) &#123;</span><br><span class="line">            //输出结果：</span><br><span class="line">            //public com.study.reflection.Cat(java.lang.String)</span><br><span class="line">            //public com.study.reflection.Cat(java.lang.String,int,java.lang.String,java.lang.String)</span><br><span class="line">            //public com.study.reflection.Cat()</span><br><span class="line">            System.out.println(c);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;==========================================================&quot;);</span><br><span class="line"></span><br><span class="line">        //获取对象的所有构造方法，</span><br><span class="line">        Constructor[] declaredConstructors = cat.getDeclaredConstructors();</span><br><span class="line">        for (Constructor dc : declaredConstructors) &#123;</span><br><span class="line">            //输出结果：</span><br><span class="line">            //public com.study.reflection.Cat(java.lang.String)</span><br><span class="line">            //public com.study.reflection.Cat(java.lang.String,int,java.lang.String,java.lang.String)</span><br><span class="line">            //public com.study.reflection.Cat()</span><br><span class="line">            System.out.println(dc);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;==========================================================&quot;);</span><br><span class="line"></span><br><span class="line">        //Cat cat1 = (Cat) cat.newInstance();//此方法在Java9之后显示已过时</span><br><span class="line">        Constructor&lt;Cat&gt; constructor = null;</span><br><span class="line">        try &#123;</span><br><span class="line">            //获取全参数构造函数</span><br><span class="line">            constructor = cat.getConstructor(String.class, int.class, String.class, String.class);</span><br><span class="line">        &#125; catch (NoSuchMethodException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        Cat cat1 = null;</span><br><span class="line">        try &#123;</span><br><span class="line">            //使用构造函数赋值初始化</span><br><span class="line">            cat1 = constructor.newInstance(&quot;花花&quot;, 2, &quot;白色&quot;, &quot;小明&quot;);</span><br><span class="line">        &#125; catch (InstantiationException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; catch (IllegalAccessException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; catch (InvocationTargetException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        //输出结果：</span><br><span class="line">        //姓名：花花, 年龄：2, 颜色：白色, 主人：小明</span><br><span class="line">        System.out.println(cat1);</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;==========================================================&quot;);</span><br><span class="line"></span><br><span class="line">        //获取指定方法，并执行，【获取的方法必须是public修饰的】</span><br><span class="line">        Method cry = null;</span><br><span class="line">        try &#123;</span><br><span class="line">            //输出结果：</span><br><span class="line">            //花花在哭</span><br><span class="line">            cry = cat.getMethod(&quot;cry&quot;);//cry()方法</span><br><span class="line">        &#125; catch (NoSuchMethodException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Object object = null;</span><br><span class="line">        try &#123;</span><br><span class="line">            object = cry.invoke(cat1);//调用cry()方法</span><br><span class="line">        &#125; catch (IllegalAccessException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; catch (InvocationTargetException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">CodingDGSun</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://sunjie23.gitee.io/codingdgsun/2021/07/06/Java%E4%B8%AD%E7%9A%84%E5%8F%8D%E5%B0%84/">https://sunjie23.gitee.io/codingdgsun/2021/07/06/Java%E4%B8%AD%E7%9A%84%E5%8F%8D%E5%B0%84/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/codingdgsun/2021/07/07/Java%E4%B8%AD%E7%9A%84%E4%BC%A0%E9%80%92%E6%98%AF%E5%80%BC%E4%BC%A0%E9%80%92/"><img class="prev-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/codingdgsun/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">Java中的传递是值传递</div></div></a></div><div class="next-post pull-right"><a href="/codingdgsun/2021/07/05/Java%E7%B1%BB%E4%B8%AD%E5%90%84%E4%B8%AA%E6%88%90%E5%91%98%E5%88%9D%E5%A7%8B%E5%8C%96%E9%A1%BA%E5%BA%8F/"><img class="next-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/codingdgsun/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">Java类中各个成员初始化顺序</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://cdn.jsdelivr.net/gh/CodingDGSun/images-db@master/Blog/头像.7horht40yvwg.jpg" onerror="this.onerror=null;this.src='/codingdgsun/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">CodingDGSun</div><div class="author-info__description"></div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/codingdgsun/archives/"><div class="headline">Articles</div><div class="length-num">59</div></a></div></div><a class="button--animated" id="card-info-btn" href="https://sunjie23.gitee.io/codingdgsun"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/codingdgsun/2022/01/17/React%E9%A1%B9%E7%9B%AEbuild%E5%A4%B1%E8%B4%A5%E4%B9%8BMiniCssExtractPlugin/" title="React项目build失败之MiniCssExtractPlugin"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/codingdgsun/img/404.jpg'" alt="React项目build失败之MiniCssExtractPlugin"/></a><div class="content"><a class="title" href="/codingdgsun/2022/01/17/React%E9%A1%B9%E7%9B%AEbuild%E5%A4%B1%E8%B4%A5%E4%B9%8BMiniCssExtractPlugin/" title="React项目build失败之MiniCssExtractPlugin">React项目build失败之MiniCssExtractPlugin</a><time datetime="2022-01-17T06:03:03.000Z" title="Created 2022-01-17 14:03:03">2022-01-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/codingdgsun/2022/01/17/React%E9%A1%B9%E7%9B%AE%E6%9E%84%E5%BB%BA%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4/" title="React项目构建常用命令"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/codingdgsun/img/404.jpg'" alt="React项目构建常用命令"/></a><div class="content"><a class="title" href="/codingdgsun/2022/01/17/React%E9%A1%B9%E7%9B%AE%E6%9E%84%E5%BB%BA%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4/" title="React项目构建常用命令">React项目构建常用命令</a><time datetime="2022-01-17T06:01:56.000Z" title="Created 2022-01-17 14:01:56">2022-01-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/codingdgsun/2022/01/17/Mac-OS%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%80%E4%B8%AAReact%E9%A1%B9%E7%9B%AE/" title="Mac OS初始化一个React项目"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/codingdgsun/img/404.jpg'" alt="Mac OS初始化一个React项目"/></a><div class="content"><a class="title" href="/codingdgsun/2022/01/17/Mac-OS%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%80%E4%B8%AAReact%E9%A1%B9%E7%9B%AE/" title="Mac OS初始化一个React项目">Mac OS初始化一个React项目</a><time datetime="2022-01-17T05:58:21.000Z" title="Created 2022-01-17 13:58:21">2022-01-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/codingdgsun/2022/01/17/MySQL%E8%AF%AD%E6%B3%95%E5%85%A5%E9%97%A8%EF%BC%88%E4%BA%8C%EF%BC%89/" title="MySQL语法入门（二）"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/codingdgsun/img/404.jpg'" alt="MySQL语法入门（二）"/></a><div class="content"><a class="title" href="/codingdgsun/2022/01/17/MySQL%E8%AF%AD%E6%B3%95%E5%85%A5%E9%97%A8%EF%BC%88%E4%BA%8C%EF%BC%89/" title="MySQL语法入门（二）">MySQL语法入门（二）</a><time datetime="2022-01-17T05:54:56.000Z" title="Created 2022-01-17 13:54:56">2022-01-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/codingdgsun/2022/01/17/Java%E4%B8%AD%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98%E4%BA%8C%EF%BC%88%E7%AE%80%E5%8D%95%EF%BC%89/" title="Java中常见面试题二（简单）"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/codingdgsun/img/404.jpg'" alt="Java中常见面试题二（简单）"/></a><div class="content"><a class="title" href="/codingdgsun/2022/01/17/Java%E4%B8%AD%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98%E4%BA%8C%EF%BC%88%E7%AE%80%E5%8D%95%EF%BC%89/" title="Java中常见面试题二（简单）">Java中常见面试题二（简单）</a><time datetime="2022-01-17T05:53:56.000Z" title="Created 2022-01-17 13:53:56">2022-01-17</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By CodingDGSun</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/codingdgsun/js/utils.js"></script><script src="/codingdgsun/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>